package com.mall.book.controller;

import com.alibaba.fastjson.JSON;
import com.mall.book.entity.po.*;
import com.mall.book.service.*;
import com.mall.book.service.impl.MultipleEvaluationsServiceImpl;
import com.mall.book.utils.JwtUtil;
import com.mall.book.wrapper.ResultWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 商品信息中心
 * 鉴权：由拦截器负责鉴权
 * 功能：向用户提供商品信息
 * Created by Dizziness on 2022/3/24 14:58
 */
@Controller
@ResponseBody
public class SKUCenter {
    @Autowired
    BookInfoService bookInfoService;

    @Autowired
    BookCategoryRelationshipService bookCategoryRelationshipService;

    @Autowired
    AuthorInfoService authorInfoService;

    @Autowired
    CategoryInfoService categoryInfoService;

    @Autowired
    CategoryGroupInfoService categoryGroupInfoService;

    @Autowired
    SaleStockService saleStockService;

    @Autowired
    BookAuthorRelationshipService bookAuthorRelationshipService;

    @Autowired
    MultipleEvaluationsService multipleEvaluationsService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 删除评论
     * @param request
     * @return
     */
    @PostMapping("/sku/withdraw")
    @Transactional
    @ResponseBody
    public ResultWrapper withdraw(HttpServletRequest request){
        String user_account = null;
        try {
            user_account = JwtUtil.verifyToken(request.getHeader("Authorization"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String evaluate_id = request.getParameter("evaluate_id");

        if (!multipleEvaluationsService.removeById(evaluate_id)) {
            throw new RuntimeException("撤销评论失败");
        }

        return ResultWrapper.builder().code(200).msg("撤销成功").build();
    }


    /**
     * 根据商品获取评论列表
     * 也能查询单用户的对某商品的评论
     * @param request
     * @return
     */
    @PostMapping("/sku/getEvaluate")
    @ResponseBody
    public ResultWrapper getEvaluate(HttpServletRequest request){
        String user_account = null;
        try {
            user_account = JwtUtil.verifyToken(request.getHeader("Authorization"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, Object> map = new HashMap<>();
        String book_id = request.getParameter("book_id");
        map.put("book_id", book_id);

        String by_user = request.getParameter("by_user");
        if(by_user != null && "1".equals(by_user)) {
            map.put("user_account", user_account);
        }

        List<MultipleEvaluations> byMap = multipleEvaluationsService.getByMap(map);

        return ResultWrapper.builder().code(200).msg("查询成功").data(byMap).build();
    }

    /**
     * 用户在订单详情页内发表评论
     * @param request
     * @return
     */
    @PostMapping("/sku/addEvaluate")
    @Transactional
    @ResponseBody
    public ResultWrapper addEvaluate(HttpServletRequest request){
        String user_account = null;
        try {
            user_account = JwtUtil.verifyToken(request.getHeader("Authorization"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, Object> params = (Map<String, Object>) JSON.parse(request.getParameter("evaluate"));
        MultipleEvaluations evaluate = new MultipleEvaluations() ;
        evaluate.setProductDescription((int)params.get("productDescription"));
        evaluate.setMerchantAttitude((int)params.get("merchantAttitude"));
        evaluate.setLogisticsService((int)params.get("logisticsService"));
        evaluate.setProfile((String)params.get("profile"));
        evaluate.setUserAccount(user_account);
        evaluate.setBookId(request.getParameter("book_id"));
        
        if (!multipleEvaluationsService.save(evaluate)) {
            throw new RuntimeException("发表评论失败");
        }
        return ResultWrapper.builder().code(200).msg("评论成功").data(evaluate).build();
    }

    /**
     * 根据类目id返回书籍
     */
    @PostMapping("/sku/getBooksByCategoryId")
    public Collection<Map<String, Object>> getBooksByCategoryId(String categoryId) {
        HashMap<String, Object> queryMap = new HashMap<>();

        //获取所有书籍信息
        queryMap.put("category_id", categoryId);
        List<BookCategoryRelationship> relationships = bookCategoryRelationshipService.getByMap(queryMap);
        queryMap.remove("category_id");//清空，方便后续复用

        //结果集
        ArrayList<Map<String, Object>> result = new ArrayList<>();

        //遍历书籍信息
        for (BookCategoryRelationship relationship  : relationships) {
            BookInfo book_info = bookInfoService.getById(relationship.getBookId());
            //去sale stock查询在售库存是否正常
            String book_id = book_info.getBookId();
            SaleStock saleStock = saleStockService.getById(book_id);

            //商品信息虽然添加了，但还未上架
            if (saleStock == null) continue;

            //库存没了，进行逻辑删除
            if (saleStock.getOnSale() == 0) {
//                saleStockService.removeById(book_id);
                continue;
                /* 可以考虑生成补货通知,然后推送到MQ中 */
                /* ********** */
            }
            //组装封装类
            HashMap<String, Object> bookWrapper = new HashMap<>();
            bookWrapper.put("onSale", saleStock.getOnSale());
            bookWrapper.put("id", book_id);
            bookWrapper.put("title", book_info.getBookTitle());
            bookWrapper.put("isbn", book_info.getBookIsbn());
            bookWrapper.put("language", book_info.getBookLanguage());
            bookWrapper.put("cover", book_info.getBookCover());
            bookWrapper.put("price", book_info.getBookPrice());
            bookWrapper.put("profile", book_info.getBookProfile());
            bookWrapper.put("totalPage", book_info.getBookTotalPage());
            bookWrapper.put("publisher", book_info.getBookPublisher());
            bookWrapper.put("publicationTime", book_info.getBookPublicationTime());
            bookWrapper.put("version", book_info.getBookVersion());
            //查询这本书下所有的作者信息
            queryMap.put("book_id", book_id);
            List<BookAuthorRelationship> a_relationships = bookAuthorRelationshipService.getByMap(queryMap);
            queryMap.remove("book_id");

            //某本书的所有作者的集合
            ArrayList<Map<String, Object>> authors = new ArrayList<>();
            for (BookAuthorRelationship a_relationship : a_relationships) {
                queryMap.put("author_id", a_relationship.getAuthorId());
                AuthorInfo authorInfo = authorInfoService.getByMap(queryMap).get(0);

                Map<String, Object> author = new HashMap<>();
                author.put("id", authorInfo.getAuthorId());
                author.put("name", authorInfo.getAuthorName());
                author.put("nationality", authorInfo.getAuthorNationality());
                author.put("profile", authorInfo.getAuthorProfile());

                authors.add(author);
            }
            bookWrapper.put("authors", authors);
            //详情图片
            Collection<String> pictures = bookInfoService.getDetailPictureById(book_id);
            bookWrapper.put("pictures", pictures);

            result.add(bookWrapper);
        }
        return result;
    }

    /**
     * 返回所有的类目分组（首页中的默认请求）
     */
    @PostMapping("/sku/getCategoryGroups")
    @ResponseBody
    public Collection<Map> getCategoryGroups() {
        //获取到所有分组信息
        HashMap<String, Object> queryMap = new HashMap<>();
        //从缓存中取数据
        Collection<CategoryGroupInfo> allGroup = categoryGroupInfoService.getByMap(queryMap);
        ArrayList<Map> result = new ArrayList<>();

        //分组信息
        for (CategoryGroupInfo categoryGroupInfo : allGroup) {
            HashMap<String, Object> group = new HashMap<>();
            group.put("id", categoryGroupInfo.getGroupId());
            group.put("name", categoryGroupInfo.getGroupName());
            //类目信息
            queryMap.put("group_id", categoryGroupInfo.getGroupId());
            Collection<CategoryInfo> categoryInfos = categoryInfoService.getByMap(queryMap);

            ArrayList<Map> categories = new ArrayList<>();
            for (CategoryInfo categoryInfo : categoryInfos) {
                HashMap<String, Object> category = new HashMap<>();
                category.put("id", categoryInfo.getCategoryId());
                category.put("name", categoryInfo.getCategoryName());
                category.put("books", "");
                categories.add(category);
            }
            group.put("categories", categories);
            result.add(group);
        }

        return result;
    }

    //销售层随机生成库存
    @PostMapping("/sku/generateStock")
    @ResponseBody
    public String generateStock() {
        //取出商品sku列表
        Collection<String> ids = bookInfoService.getAllIds();
        for (String id : ids) {
            SaleStock saleStock = new SaleStock();
            saleStock.setBookId(id);
            saleStock.setOnSale((int) (Math.random() * 100) + 100);
            boolean save = saleStockService.save(saleStock);
            System.out.println(saleStock);
        }
        return "done";
    }

    //添加作者
    @PostMapping("/sku/addAuthor")
    public boolean addAuthor(@RequestBody AuthorInfo authorInfo) {
        return authorInfoService.save(authorInfo);
    }

    //添加类目
    @PostMapping("/sku/addCateGory")
    public boolean addCateGory(@RequestBody CategoryInfo categoryInfo) {
        return categoryInfoService.save(categoryInfo);
    }

    //添加类目分組
    @PostMapping("/sku/addCategoryGroup")
    public boolean addCategoryGroup(@RequestBody CategoryGroupInfo categoryGroupInfo) {
        return categoryGroupInfoService.save(categoryGroupInfo);
    }
}
